package cn.yanhu.kuwanapp.utils.third

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import cn.woochen.comlib.util.UserPref
import cn.yanhu.kuwanapp.R
import cn.yanhu.kuwanapp.utils.Config
import cn.yanhu.kuwanapp.utils.constans.Constants
import cn.yanhu.kuwanapp.utils.ext.logcom
import cn.yanhu.kuwanapp.utils.ext.showToast
import com.tencent.connect.share.QQShare
import com.tencent.connect.share.QzoneShare
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import java.io.ByteArrayOutputStream


/**
 *微信登录
 *@author woochen
 *@time 2019/5/22 15:13
 */
object ThirdAccountHelper {
     lateinit var wxApi: IWXAPI
     lateinit var mTencent: Tencent

    fun init(context: Context){
        regToWx(context)
        regToQQ(context)
    }


    /**
     * 将app注册到微信
     */
   private  fun regToWx(context: Context) {
        wxApi = WXAPIFactory.createWXAPI(context, Config.WX_APP_ID, true)
        context.registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context, intent: Intent) {
                // 将该app注册到微信
                wxApi.registerApp(Config.WX_APP_ID)
            }
        }, IntentFilter(ConstantsAPI.ACTION_REFRESH_WXAPP))
    }

    /**
     * 将app注册到QQ
     */
    private fun regToQQ(context: Context){
        if (context.applicationContext == null) return
        mTencent = Tencent.createInstance(Config.QQ_APP_ID, context.applicationContext,"${context.packageName}.fileprovider")
    }


    /**
     * 发送微信登录授权码
     * @param accountType 账号类型
     */
    fun sendAuthReq(accountType: AccountType,operateType:String =AccountReqType.LOGIN) {
        when (accountType) {
            AccountType.WX -> {
                val req = SendAuth.Req()
                req.transaction = operateType
                req.scope = "snsapi_userinfo"
                req.state = "wechat_sdk_xsk"
                wxApi.sendReq(req)
            }
        }
    }

    /**
     * 分享图片
     */
    fun sharePic(context: Context, shareChannel: AccountShareType, bitmap: Bitmap?, thumbBitmap: Bitmap = BitmapFactory.decodeResource(context.applicationContext.resources, R.drawable.ic_share_logo)){
        if (bitmap == null){
            showToast("生成海报失败，分享失败!")
            return
        }
        when (shareChannel) {
            AccountShareType.WX_CIRCLE  -> {//微信朋友圈
                val imgObj = WXImageObject(bitmap)
                val msg = WXMediaMessage()
                msg.mediaObject = imgObj
                val thumbBmp = Bitmap.createScaledBitmap(bitmap, bitmap.width/20, bitmap.height/20, true)
                bitmap.recycle()
                msg.thumbData = bitmap2Bytes(thumbBmp)
                val req = SendMessageToWX.Req()
                req.message = msg
                req.transaction = AccountReqType.SHARE
                req.scene = SendMessageToWX.Req.WXSceneTimeline
                wxApi.sendReq(req)
            }
            AccountShareType.WX_SESSION  -> {//微信好友
                val imgObj = WXImageObject(bitmap)
                val msg = WXMediaMessage()
                msg.mediaObject = imgObj
                val thumbBmp = Bitmap.createScaledBitmap(bitmap, bitmap.width/20, bitmap.height/20, true)
                msg.thumbData = bitmap2Bytes(thumbBmp)
                val req = SendMessageToWX.Req()
                req.message = msg
                req.transaction = AccountReqType.SHARE
                req.scene = SendMessageToWX.Req.WXSceneSession
                wxApi.sendReq(req)
                bitmap.recycle()
            }
            AccountShareType.QQ  -> {//qq
                val params = Bundle()
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_IMAGE)
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_LOCAL_URL, Constants.posterLocalPath)
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME,context.resources.getString(R.string.app_name))
                mTencent.shareToQQ(context as Activity, params, object : IUiListener {
                    override fun onComplete(p0: Any?) {

                    }

                    override fun onCancel() {

                    }

                    override fun onWarning(code: Int) {
                        logcom("onWarning手q权限:${code}")
                    }

                    override fun onError(p0: UiError?) {

                    }
                })
            }
        }

    }

    private var mSharaTitle= "加入酷爱玩,边玩边看边赚钱！"
    private var mSharaSubtitle= "【酷爱玩】玩玩小游戏就能赚钱，1元提现秒到账，在家躺着也赚钱！"




    /**
     * 分享网页链接
     */
    fun sharePageLink(context: Context, title:String= mSharaTitle, description:String= mSharaSubtitle, url:String="", shareChannel: AccountShareType, bitmap: Bitmap = BitmapFactory.decodeResource(context.applicationContext.resources, R.drawable.ic_share_logo)){
        when (shareChannel) {
            AccountShareType.WX_CIRCLE  -> {//微信朋友圈
                val webpage = WXWebpageObject()
                webpage.webpageUrl = url
                val msg = WXMediaMessage(webpage)
                msg.title = title
                msg.description = description
                msg.thumbData = bitmap2Bytes(bitmap)
                val req = SendMessageToWX.Req()
                req.transaction = AccountReqType.SHARE
                req.message = msg
                req.scene = SendMessageToWX.Req.WXSceneTimeline
                wxApi.sendReq(req)

            }
            AccountShareType.WX_SESSION  -> {//微信会话
                val webpage = WXWebpageObject()
                webpage.webpageUrl = url
                val msg = WXMediaMessage(webpage)
                msg.title = title
                msg.description = description
                msg.thumbData = bitmap2Bytes(bitmap)
                val req = SendMessageToWX.Req()
                req.transaction = AccountReqType.SHARE
                req.message = msg
                req.scene = SendMessageToWX.Req.WXSceneSession
                //        req.userOpenId = getOpenId()
                wxApi.sendReq(req)

            }

            AccountShareType.QQ ->{//QQ
                val params = Bundle()
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT)
                params.putString(QQShare.SHARE_TO_QQ_TITLE, title)
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, url)
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, description)
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, context.resources.getString(R.string.app_name))
                mTencent.shareToQQ(context as Activity, params, object : IUiListener {
                    override fun onComplete(p0: Any?) {

                    }

                    override fun onCancel() {

                    }

                    override fun onWarning(p0: Int) {

                    }

                    override fun onError(p0: UiError?) {

                    }
                })
            }
            AccountShareType.QQ_CIRCLE -> {
                val params = Bundle()
                params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT)
                params.putString(QzoneShare.SHARE_TO_QQ_TITLE,title)//必填
                params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, description)//选填
                params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, url)//必填
                mTencent.shareToQzone(context as Activity, params, object : IUiListener {
                    override fun onComplete(p0: Any?) {

                    }

                    override fun onCancel() {

                    }

                    override fun onWarning(p0: Int) {

                    }

                    override fun onError(p0: UiError?) {

                    }
                })
            }

        }
    }

    /**
     * 跳转到小程序
     * @param context Context
     */
    fun jumpToMiniProgram(context: Context,userName:String,path:String){
       // 填移动应用(App)的 AppId，非小程序的 AppID
        val api = WXAPIFactory.createWXAPI(context, Config.WX_APP_ID)
        val req = WXLaunchMiniProgram.Req()
        req.userName = userName// 填小程序原始id
        req.path = path ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
        api.sendReq(req)
    }


    /**
     * 把Bitmap转Byte
     * @Author HEH
     * @EditTime 2010-07-19 上午11:45:56
     */
    fun bitmap2Bytes(bm: Bitmap): ByteArray {
        val baos = ByteArrayOutputStream()
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos)
        return baos.toByteArray()
    }


}